package org.ttitfly.ttcore.util.query;

import java.util.Map;

import org.ttitfly.ttcore.util.WebConstants;

import com.opensymphony.xwork2.ActionContext;

// TODO this class is never used
public class PageHelper {

    private ActionContext context;

    private Object so;

    public PageHelper(ActionContext context, Object so) {

        this.context = context;
        this.so = so;

        if (so instanceof Pagable) {
            ((Pagable) so).setCurrentPage(getCurrentPage() - 1);
        }
        if (so instanceof Sortable) {
            Sort sort = new Sort();
            sort.setSortKey(getSort());
            sort.setSortDir(getDir());
            ((Sortable) so).addSort(sort);
        }

    }

    public Object getSo() {
        return so;
    }

    public int getPageSize() {
        return ((Pagable) so).getPageSize();
    }

    public int getCurrentPage() {
        int page = 1;
        if (context.getParameters().get(WebConstants.PAGE) != null) {
            page = Integer.parseInt(((String[]) ActionContext.getContext().getParameters().get(WebConstants.PAGE))[0]);
        }
        return page;
    }

    @SuppressWarnings("unchecked")
    public boolean getExportFull() {
        boolean export = false;
        Map map = context.getParameters();
        for (Object o : map.keySet()) {
            if (o.toString().matches(WebConstants.REGEX)) {
                if (map.get(o) != null) {
                    export = true;
                }
            }
        }
        return export;
    }

    public String getSort() {
        String sort = null;
        if (context.getParameters().get(WebConstants.SORT) != null) {
            sort = ((String[]) ActionContext.getContext().getParameters().get(WebConstants.SORT))[0];
        }
        return sort;
    }

    public String getDir() {
        String dir = null;
        if (context.getParameters().get(WebConstants.DIR) != null) {
            dir = ((String[]) ActionContext.getContext().getParameters().get(WebConstants.DIR))[0];
        }
        return dir;
    }

}
